<?php

namespace App\Api\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use DateTimeInterface;

class MaterielClassModel extends Model
{
    use HasFactory;

    protected $table = 'materiel_class';
    protected $dateFormat = 'U';//这个时间字段被为被格式化为UNIX 时间戳的形式存储

    //toArray 时间转换问题
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function nextClass()
    {
        return SELF::hasMany(SELF::class, 'parent_id', 'id');
    }

    public function nextType()
    {
        return SELF::hasMany(MaterielTypeModel::class, 'materiel_class_id', 'id');
    }

    //获取物料完整分类信息
    static public function getMaterielAndClassInfo($parentId, $condition, $keyword, $data)
    {
        return SELF::select(
            'a.id as f_id',
            'b.id as s_id',
            'b.parent_id',
            'c.id as t_id',
            'c.materiel_class_id',
        )
            ->from('materiel_class as a')
            ->leftJoin('materiel_class as b', 'b.parent_id', '=', 'a.id')
            ->leftJoin('materiel_type as c', 'c.materiel_class_id', 'b.id')
            ->where('a.main_id', $parentId)
            ->where('a.delete_flag', 0)
            ->where('b.delete_flag', 0)
            ->where('a.delete_flag', 0)
            ->where($condition)
            ->where(function($query) use ($keyword) {
                $query->orWhere('a.class_name', 'LIKE', '%'.$keyword.'%');
                $query->orWhere('b.full_class_no', 'LIKE', '%'.$keyword.'%');
                $query->orWhere('a.class_no', 'LIKE', '%'.$keyword.'%');
                $query->orWhere('b.class_name', 'LIKE', '%'.$keyword.'%');
                $query->orWhere('b.class_no', 'LIKE', '%'.$keyword.'%');
                $query->orWhere('c.materiel_name', 'LIKE', '%'.$keyword.'%');
                $query->orWhere('c.type_name', 'LIKE', '%'.$keyword.'%');
                $query->orWhere('c.materiel_no', 'LIKE', '%'.$keyword.'%');
            })
            ->orderBy('a.id', 'DESC')
            ->limit($data['pageSize'])->offset(--$data['currentPage'] * $data['pageSize'])
            ->get()->toArray();
    }

    static public function checkMaterielClassCode($classNo, $parentId)
    {
        return SELF::where([
            'delete_flag' => 0,
            'class_no' => $classNo,
            'main_id' => $parentId
        ])
            ->first();
    }
}
